import * as $ from 'jquery';
import {HttpQueryParamsDto} from '../lunhui-web-front-dto/HttpQueryParamsDto';

export class HttpUtil {

    public static query(params: HttpQueryParamsDto): Promise<object> {
        return new Promise((resolve) => {
            $.ajax({
                url: params.url,
                contentType: params.contentType,
                method: params.method,
                success: (data) => {
                    HttpUtil.loadingEnd();
                    resolve(data);
                },
                error: (error) => {
                    HttpUtil.queryError(error.statusText);
                    HttpUtil.loadingEnd();
                },
                beforeSend: () => {
                    HttpUtil.loadingStart();
                }
            });
        });
    }

    private static loadingStart(): void {
        $('body').append('<div class="progress"><div></div></div>');

        $('.progress').css({
            position: 'fixed',
            top: 0,
            left: 0,
            width: '100%',
            height: '3px'
        });

        const progressCtx = $('.progress div');
        progressCtx.css({
            width: '10%',
            height: '100%',
            boxSizing: 'border-box',
            borderRadius: '0 2px 2px 0',
            backgroundColor: 'rgba(255, 114, 0, 0.6)'
        });

        progressCtx.animate({width: '99%'}, 3000);
    }

    private static loadingEnd(): void {
        const progress = $('.progress');

        if (progress) {
            const progressCtx = $('.progress div');

            progressCtx.stop();

            progressCtx.animate({width: '100%'}, 300, () => {
                progress.remove();
            });
        }
    }

    public static queryError(errorMessage: string): void {
        const body = $('body');
        body.append(`<div class="errorTos"><span>${errorMessage}</span>`);
        const bw = body.width();
        const bh = body.height();

        const errorTos = $('.errorTos');

        errorTos.css({
            position: 'fixed',
            top: bh / 2 - 40,
            left: bw / 2 - 80,
            width: '160px',
            height: '80px',
            overFlow: 'hidden',
            backgroundColor: 'rgba(62,62,62,0.89)',
            borderRadius: '5px',
            color: 'rgb(252,255,254)',
            textAlign: 'center',
            paddingTop: '20px',
            fontSize: '14px'
        });

        errorTos.fadeOut(2000);
        const timer: number = setTimeout(() => {
            errorTos.remove();
            clearTimeout(timer);
        }, 2000);
    }
}
